/**
 * @Author cheng
 * @Date 2022 11 06 21 49
 **/

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;
import java.util.Random;

public class KafkaDemo {
    public static void main(String[] args) {

        // 1. 创建 kafka 生产者的配置对象
        Properties properties = new Properties();
        // 2. 给 kafka 配置对象添加配置信息：bootstrap.servers
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.238.99:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");


        // 每隔5秒推送 5条数据
        while (true) {
            // 3. 创建 kafka 生产者对象
            KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);
            System.out.println("开始发送数据==========================");
            try {
                // 4. 调用 send 方法,发送消息
                for (int i = 0; i < 5; i++) {
                    Random rd=new Random();  //创建实例
                    // 品类
                    String[] categoryArray = new String[]{"连衣裙", "帆布鞋", "YSL", "耐克", "数码"};
                    int radom =rd.nextInt(4);
                    String category  = categoryArray[radom];
                    // 模拟数据
                    System.out.println("发送数据为" + category);

                    try {
                    kafkaProducer.send(new ProducerRecord<String, String>("15homework", category));

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                Thread.sleep(2000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            // 5. 关闭资源
            kafkaProducer.close();

        }

    }
}
